import {
  Body,
  Controller,
  Get,
  HttpCode,
  HttpStatus,
  Post,
  Query,
  Res,
  UploadedFiles,
  UseInterceptors,
} from '@nestjs/common';
import { LargeFileUploadService } from './large-file-upload.service';
import { FilesInterceptor } from '@nestjs/platform-express';
import * as fs from 'fs';

@Controller('large-file-upload')
export class LargeFileUploadController {
  constructor(
    private readonly largeFileUploadService: LargeFileUploadService,
  ) {}

  @Post('upload')
  @UseInterceptors(
    FilesInterceptor('files', 20, {
      dest: 'uploads',
    }),
  )
  @HttpCode(200)
  uploadFiles(
    @UploadedFiles() files: Array<Express.Multer.File>,
    @Body() body,
    @Res() res,
  ) {
    console.log('--body.name--', body.name);
    const fileName = body.name.match(/(.+)\-\d+$/)[1];
    console.log('--fileName--', fileName);
    const chunkDir = 'uploads/chunks_' + fileName;
    console.log('--chunkDir--', chunkDir);
    console.log('--files[0].path--', files[0].path); //指向该文件在服务器上的临时存储路径
    if (!fs.existsSync(chunkDir)) {
      fs.mkdirSync(chunkDir);
    }

    fs.cpSync(files[0].path, chunkDir + '/' + body.name); // 保存分片文件
    fs.rmSync(files[0].path); // 删除临时文件
    res.send({
      retcode: HttpStatus.OK,
      retmsg: '创建成功',
      data: '',
    });
  }

  @Get('merge')
  merge(@Query('name') name: string) {
    const chunkDir = 'uploads/chunks_' + name;
    let files = fs.readdirSync(chunkDir);
    let count = 0;
    let startPos = 0;
    // 排序
    files = files.sort((a: any, b: any) => {
      return a.split('-')?.[1] - b.split('-')?.[1];
    });
    files.map((file) => {
      const filePath = chunkDir + '/' + file;
      const stream = fs.createReadStream(filePath);
      stream
        .pipe(
          fs.createWriteStream('uploads/' + name, {
            start: startPos,
          }),
        )
        .on('finish', () => {
          count++;
          if (count === files.length) {
            // todo 上传minio
            console.log('上传minio');
            // this.largeFileUploadService.uploadMinio('uploads/' + name);
            fs.rmdirSync(chunkDir, { recursive: true });
          }
        });
      startPos += fs.statSync(filePath).size;
    });
  }
}
